package com.aos.service.role.impl;

import com.aos.dao.*;
import com.aos.dto.PermissionDto;
import com.aos.dto.RoleDto;
import com.aos.dto.parameters.RoleParameter;
import com.aos.entity.Application;
import com.aos.entity.Role;
import com.aos.entity.RolePermission;
import com.aos.service.role.RoleService;
import com.aos.util.CopyUtils;
import com.aos.util.Result;
import com.aos.util.TreeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @ClassName RoleServiceImpl
 * @Description:角色业务
 * @Author wumingwang
 * @Date 2018/9/9 17:39
 * @Version 1.0
 */
@Service
@Slf4j
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Autowired
    private ApplicationDao applicationDao;

    @Override
    public Result queryByPage(Map<String, Object> map) {
        /**开启分页查询，sql的执行要紧跟这个分页工具*/
        PageHelper.startPage((int)map.get("pageNum"),(int)map.get("pageSize"));
        List<RoleDto> list =  roleDao.queryByPage(map);
        PageInfo<RoleDto> p = new PageInfo<>(list);
        return Result.ok(p);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addRole(RoleParameter roleParameter) {
        Role role = new Role();
        try{
            CopyUtils.copy(roleParameter,role);
        }catch (Exception e){
            log.error("属性复制错误！",e);
            return Result.error("系统繁忙，请稍后再试！");
        }
        RoleDto rd = roleDao.queryForCheckByNameAndAppId(role);
        if(rd != null){
            return Result.error("应用："+rd.getAppName()+"下该角色已存在！");
        }
        roleDao.insert(role);
        /**保存角色菜单关联关系*/
        Set<Long> roleSet = new HashSet<>(Arrays.asList(roleParameter.getPermissions()));
        for(Long pid : roleSet){
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPermissionId(pid);
            rolePermission.setRoleId(role.getId());
            rolePermissionDao.insert(rolePermission);
        }
        return Result.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteById(Long id) {
        if(userRoleDao.queryByRoleId(id) != null){
            return Result.error("该角色有用户正在使用中，不可删除！");
        }
        roleDao.delete(id);
        /**删除角色菜单关联关系*/
        rolePermissionDao.deleteByRoleId(id);
        return Result.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateRole(RoleParameter roleParameter) {
        Role role = new Role();
        try{
            CopyUtils.copy(roleParameter,role);
        }catch (Exception e){
            log.error("属性复制错误！",e);
            return Result.error("系统繁忙，请稍后再试！");
        }
        RoleDto rd = roleDao.queryForCheckByNameAndAppId(role);
        if(rd != null){
            return Result.error("应用："+rd.getAppName()+"下该角色已存在！");
        }
        roleDao.update(role);
        /**删除角色菜单关联关系*/
        rolePermissionDao.deleteByRoleId(role.getId());
        /**保存角色菜单关联关系*/
        Set<Long> roleSet = new HashSet<>(Arrays.asList(roleParameter.getPermissions()));
        for(Long pid : roleSet){
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPermissionId(pid);
            rolePermission.setRoleId(role.getId());
            rolePermissionDao.insert(rolePermission);
        }
        return Result.ok();
    }

    @Override
    public Result queryDetails(Long id) {
        Map<String,Object> map = new HashMap<>();
        RoleDto rd = roleDao.queryDetailsById(id);
        if(rd != null){
            map.put("role",rd);
            List<PermissionDto> list = permissionDao.queryListByAppIdAndRoleId(rd.getApplicationId(),rd.getId());
            map.put("permissionsTree", TreeUtils.buildTree(list));
        }
        return Result.ok(map);
    }

    @Override
    public Result queryListByAppId(Long appId,Long userId) {
        return Result.ok(roleDao.queryRolesByAppAndUser(userId,appId));
    }

    @Override
    public Result addRoleByAppCode(RoleParameter roleParameter) {
        Application app = applicationDao.queryByCode(roleParameter.getAppCode());
        if(app == null){
            return Result.error("应用不存在，无法创建");
        }
        roleParameter.setApplicationId(app.getId());
        return addRole(roleParameter);
    }

    @Override
    public Result queryListByAppCode(String appCode, Long userId) {
        Application app = applicationDao.queryByCode(appCode);
        if(app == null){
            return Result.error("应用不存在!");
        }
        return queryListByAppId(app.getId(),userId);
    }
}
